<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Request\UserLoginRequest;
use App\Request\UserPasswordRequest;
use App\Request\UserRegisterRequest;
use App\Request\UserSaveRequest;
use App\Service\Dao\UserDao;
use App\Service\Formatter\UserFormatter;
use App\Service\Redis\UserAuth;
use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;

class UserController extends Controller
{
    /**
     * @Inject
     * @var UserService
     */
    protected $service;

    /**
     * @Inject
     * @var UserDao
     */
    protected $dao;

    /**
     * @Inject
     * @var UserFormatter
     */
    protected $formatter;

    public function register(UserRegisterRequest $request)
    {
        $mobile = $request->input('mobile');
        $type = (int) $request->input('type');
        $code = $request->input('code');

        $user = $this->service->register($mobile, $type, $code);
        $userAuth = UserAuth::instance()->init($user);
        return $this->response->success([
            'id' => $user->id,
            'registered' => $user->registered(),
            'token' => $userAuth->token,
        ]);
    }

    public function save(UserSaveRequest $request)
    {
        $userAuth = UserAuth::instance()->build();
        $input = $request->all();

        $user = $this->service->save($userAuth->userId, $input);

        return $this->response->success(
            $this->formatter->info($user)
        );
    }

    public function login(UserLoginRequest $request)
    {
        $mobile = $request->input('mobile');
        $type = (int) $request->input('type');
        $code = $request->input('code');

        $user = $this->service->login($mobile, $type, $code);
        $userAuth = UserAuth::instance()->init($user);

        return $this->response->success([
            'id' => $user->id,
            'registered' => $user->registered(),
            'token' => $userAuth->token,
        ]);
    }

    public function password(UserPasswordRequest $request)
    {
        $password = $request->input('password');
        $userAuth = UserAuth::instance()->build();

        $result = $this->service->password($userAuth->userId, $password);

        return $this->response->success([
            'updated' => $result,
        ]);
    }

    public function info()
    {
        $userAuth = UserAuth::instance()->build();

        $user = $this->dao->first($userAuth->userId, true);

        return $this->response->success(
            $this->formatter->info($user)
        );
    }
}
